import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Ref, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { AcquisitionManageContext, IAcquisitionActionEnum } from '.';
import { materialTableService } from '../services/ModalServices';

import { Button, message } from 'antd';
import { getUserDepID, onCloseModalCommon } from '@/utils';
import { showTotalInfo } from '@/common/constVariable';
import { UpdateTableCommon } from './UpdateTableCommon';
import { AssetacquisitionManageAPI } from '../common/type';
import { getMaterialModalColumns } from './ModalColumns';
import _ from 'lodash';
import moment from 'moment';

/** 领用/退库 表单页 选择材料-模态框 */
export const OpenMaterialModal: React.FC<AssetacquisitionManageAPI.IOpenMaterialModal> = ({ onClose, isShowModal, queryType, BelongDepartmentID }) => {
  /** 货物归属部门ID */
  const [belongID, setBelongID] = useState();

  /**弹框的ref*/
  const updateModalRef: Ref<IOneModalRef> = useRef(null);

  /** 根样式 */
  const styleFixCls = 'contract-styfixcls-';

  /**管理页Ref*/
  const ManagePageRef = useRef<Record<string, any>>(null);

  useEffect(() => {
    if (belongID && ManagePageRef?.current?.getSearchRun) {
      if (belongID === getUserDepID()) {
        ManagePageRef?.current?.getSearchRun({ sharing: '0' });
      } else {
        ManagePageRef?.current?.getSearchRun({ sharing: '1' });
      }
    }
  }, [belongID, ManagePageRef]);

  /** 获取上下文 */
  const { curRes, acquisitionDispatch, materialList } = useContext(AcquisitionManageContext);

  /** 获取列表 */
  const { dataList, params, loading, pagination, searchList, getManageData } = materialTableService(curRes, 0, queryType, false, belongID);

  /** 解析保存货物归属部门ID */
  useEffect(() => {
    BelongDepartmentID()?.then((res) => {
      setBelongID(res);
    });
  }, [BelongDepartmentID]);

  /** 暂时保存选中的值 */
  const [checkMaterialList, setCheckMaterialList] = useState<Record<string, any>[]>([]);

  /** 表格数据 */
  const [dataSource, setDataSource] = useState<Record<string, any>[]>([]);

  useEffect(() => {
    if (dataList?.length) {
      let dataRow: Record<string, any>[] = [];
      dataRow = _.cloneDeep(dataList);
      // 添加总价和数量字段
      for (let i = 0; i < dataRow.length; i++) {
        dataRow[i].quantityOrArea = dataRow[i].hasOwnProperty('residueNum') ? dataRow[i].residueNum : dataRow[i].quantityOrArea;
        dataRow[i].materialOrAssetId = dataRow[i].id;
      }
      if (materialList.length !== 0) {
        for (let i = 0; i < materialList.length; i++) {
          let idx = dataRow.findIndex((item: Record<string, any>) => {
            return item.materialOrAssetId === materialList[i].materialOrAssetId;
          });
          if (idx !== -1) {
            dataRow[idx].quantityOrArea = Number(materialList[i].quantityOrArea);
            dataRow[idx].location = checkMaterialList[i].location;
            dataRow[idx].locationInfo = checkMaterialList[i].locationInfo;
          }
        }
      }
      setDataSource(dataRow);
    } else {
      setDataSource([]);
    }
  }, [dataList]);

  /** 搜索 */
  const onSearch = (payload: Record<string, any>) => {
    getManageData({ ...payload, current: 1, pageSize: 10 });
  };

  /** 重置 */
  const onReset = (payload: Record<string, any>) => {
    if (belongID && ManagePageRef?.current?.getSearchRun) {
      if (belongID === getUserDepID()) {
        ManagePageRef?.current?.getSearchRun({ sharing: '0' });
      } else {
        ManagePageRef?.current?.getSearchRun({ sharing: '1' });
      }
    }
  };

  /** 分页change 方法 */
  const onPageChange = (current: number, pageSize: number) => {
    getManageData({ ...params, current, pageSize });
  };

  /** 点击选中 */
  const onSelectTable = (selectInfo) => {
    setCheckMaterialList(selectInfo);
  };

  /** 初始化 */
  useEffect(() => {
    setCheckMaterialList(materialList);
  }, [isShowModal]);

  /** 修改材料数量 */
  const changeNum = (id: string | number, value: string | number) => {
    /** 修改表格材料数量 */
    let idx = dataSource.findIndex((item: Record<string, any>) => {
      return item.id === id;
    });
    if (idx !== -1) {
      let arr = _.cloneDeep(dataSource);
      arr[idx].quantityOrArea = value;
      setDataSource(arr);
    }
    /** 修改选中材料数量 */
    let checkIdx = checkMaterialList.findIndex((item: Record<string, any>) => {
      return item.materialOrAssetId === id;
    });
    if (checkIdx !== -1) {
      let arr = _.cloneDeep(checkMaterialList);
      arr[checkIdx].quantityOrArea = value;
      if (arr[checkIdx].residueNum) {
        arr[checkIdx].expectNum = arr[checkIdx].residueNum - arr[checkIdx].quantityOrArea;
      } else {
        arr[checkIdx].expectNum = dataSource[checkIdx].residueNum - arr[checkIdx].quantityOrArea;
      }
      setCheckMaterialList(arr);
    }
  };

  /** 点击确定 */
  const onSave = () => {
    if (checkMaterialList && checkMaterialList?.length > 0) {
      // 存储到仓库
      acquisitionDispatch({
        type: IAcquisitionActionEnum.SELECT_MATERIAL,
        payload: checkMaterialList,
      });
      onCloseModalCommon(updateModalRef);
    } else {
      message.error('请至少选择一个材料');
    }
    return;
  };

  const [isNextBtn, setisNextBtn] = useState(false);

  const setisNextBtnFun = (isNextBtn: boolean) => {
    setisNextBtn(isNextBtn);
  };

  const modelFooter = () => {
    return (
      <>
        <Button onClick={onSave} disabled={checkMaterialList?.length === 0 || isNextBtn}>
          确定
        </Button>
      </>
    );
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={updateModalRef}
        title={'选择材料'}
        onCancel={onClose}
        width={document.body.clientWidth * 0.85}
        bodyStyle={{
          height: document.body.clientHeight * 0.65,
          padding: 10,
        }}
        // onOk={onSave}
        footer={modelFooter()}
      >
        <div className="asset_apply_selectAssetModalBox">
          <UpdateTableCommon
            ref={ManagePageRef}
            styleFixCls={styleFixCls}
            searchProps={{
              searchList,
              onReset,
              onSearch,
            }}
            selectTablePorps={{
              onSelectTable,
              selectRowObjList: checkMaterialList,
              selectType: 'checkbox',
              setCheckRows: setCheckMaterialList,
              getCheckboxProps: (record: Record<string, any>) => ({
                disabled: record.quantityOrArea <= 0,
              }),
            }}
            tableProps={{
              columns: getMaterialModalColumns({ changeNum, setisNextBtnFun, queryType }),
              loading,
              dataSource: dataSource,
              pagination,
              onPageChange,
              rowKey: 'materialOrAssetId',
              tableTotalShow: (total: any, range: any) => {
                return (
                  <div
                    style={{
                      display: 'flex',
                      width: '100%',
                      justifyContent: 'space-between',
                    }}
                  >
                    <div>
                      已选择<strong style={{ color: 'red' }}> {checkMaterialList?.length} </strong>条材料
                    </div>
                    <div>{showTotalInfo(total, range)}</div>
                  </div>
                );
              },
            }}
          />
        </div>
      </OneModal>
    </>
  );
};
